package com.cwj.scalableIO.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: Chenwujie
 * @date: 2021-07-20 14:44
 */
public class BioServer {
    private static final int PORT = 6666;
    private static final int MAX_INPUT = 1024;
    private static final ExecutorService  executorService =
        Executors.newCachedThreadPool();
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            while (true){
                executorService.execute(new Handler(serverSocket.accept()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class Handler implements Runnable{
        private Socket socket;

        public Handler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            byte[] data = new byte[MAX_INPUT];
            try {
                socket.getInputStream().read(data);
                byte[] output = process(data);
                socket.getOutputStream().write(output);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private byte[] process(byte[] output){
            return "success".getBytes();
        }
    }
}
